package com.zf.shuashua.ui.home;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.utils.ToastUtil;
import com.bumptech.glide.Glide;
import com.lxj.easyadapter.EasyAdapter;
import com.lxj.easyadapter.MultiItemTypeAdapter;
import com.lxj.easyadapter.ViewHolder;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lxj.xpopup.util.KeyboardUtils;
import com.lxj.xpopup.util.XPopupUtils;
import com.lxj.xpopup.widget.VerticalRecyclerView;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.R;
import com.zf.shuashua.api.AbsCallback;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.bean.CommentBean;
import com.zf.shuashua.bean.ReplyStoreBean;
import com.zf.shuashua.bean.StoreBean;
import com.zf.shuashua.ui.mine.LoginActivity;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**lxd
 * 评论窗口
 *
 */
public class TikTokCommentPopup extends BottomPopupView {
    VerticalRecyclerView recyclerView;
    private List<CommentBean.DataBean> list = new ArrayList<>();
    private EasyAdapter<CommentBean.DataBean> commonAdapter;
    private int mVideoId;
    private String mAvatarUrl;
    private Context mContext;
    private EditText etComment;
    private TextView tvNumber;
    //1.评论 2.评论回复
    private int TAG =0 ;
    private CommentBean.DataBean dataBean;
    public TikTokCommentPopup(@NonNull Context context) {
        super(context);
    }
    public TikTokCommentPopup(@NonNull Context context,int videoId,String avatarUrl) {
        super(context);
        this.mContext = context;
        this.mVideoId = videoId;
        this.mAvatarUrl = avatarUrl;
    }
    @Override
    protected int getImplLayoutId() {
        return R.layout.lxd_custom_bottom_popup;
    }
    @Override
    protected void onCreate() {
        super.onCreate();
        getComment();
        recyclerView = findViewById(R.id.recyclerView);
        tvNumber = findViewById(R.id.tv_number);
        ImageView avatar = findViewById(R.id.avatar);
        if(TextUtils.isEmpty(mAvatarUrl) ||mAvatarUrl == null) {
            avatar.setImageDrawable(mContext.getDrawable(R.mipmap.lxd_icon_avatar));
        }else {
            Glide.with(mContext)
                    .load(mAvatarUrl)
                    .placeholder(R.mipmap.ic_launcher)
                    .into(avatar);
        }


        findViewById(R.id.img_del).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        etComment =  findViewById(R.id.et_comment);

        etComment.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.isEmpty(ShuaApplication.token)) {
                    mContext.startActivity(new Intent(mContext, LoginActivity.class));
                    dismiss();
                }
            }
        });
        etComment.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    if(TAG == 0) {
                        toStore();
                    }else if(TAG == 1) {
                        replyStore();
                    }

                }
                return false;
            }
        });

        /*findViewById(R.id.tv_temp).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹出新的弹窗用来输入
                final CustomEditTextBottomPopup textBottomPopup = new CustomEditTextBottomPopup(getContext());
                new XPopup.Builder(getContext())
                        .autoOpenSoftInput(true)
                        .hasShadowBg(false)
                        .setPopupCallback(new SimpleCallback() {
                            @Override
                            public void onShow() {
                            }

                            @Override
                            public void onDismiss() {
                                String comment = textBottomPopup.getComment();
                                if (!comment.isEmpty()) {
                                    data.add(0, comment);
                                    commonAdapter.notifyDataSetChanged();
                                }
                            }
                        })
                        .asCustom(textBottomPopup)
                        .show();
            }
        });*/
       /* for (int i = 0; i < 15; i++) {
            data.add("这个就很棒啊！就很棒！");
        }*/
        commonAdapter = new EasyAdapter<CommentBean.DataBean>(list, R.layout.lxd_adapter_tiktok_comment) {
            @Override
            protected void bind(@NonNull final ViewHolder holder, @NonNull CommentBean.DataBean data, final int position) {
                final List<CommentBean.DataBean.ReplysBean> replys = data.getReplys();
                List<CommentBean.DataBean.ReplysBean> firstReplys =new ArrayList<>();

                Glide.with(mContext)
                        .load(data.getUser().getAvatar())
                        .placeholder(R.mipmap.ic_launcher)
                        .into((ImageView) holder.getView(R.id.avatar));

                holder.setText(R.id.name, data.getUser().getName())
                        .setText(R.id.comment, data.getContent())
                        .setText(R.id.tv_time,data.getCreated_time())
                        .setText(R.id.tv_comment_number,String.valueOf(data.getPraise_count()));

                holder.getView(R.id.tv_more).setVisibility(GONE);
                if(replys.size()>0) {
                    if(replys.size()>1) {
                        holder.getView(R.id.tv_more).setVisibility(VISIBLE);
                    }
                    firstReplys.add(replys.get(0));
                    RecyclerView recyclerView = holder.getView(R.id.recyclerView);
                    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
                    recyclerView.setLayoutManager(linearLayoutManager);
                    final CommentReturnAdapter commentReturnAdapter = new CommentReturnAdapter(R.layout.layout_adapter_score_comment,firstReplys);
                    recyclerView.setAdapter(commentReturnAdapter);
                    commentReturnAdapter.notifyDataSetChanged();
                    holder.getView(R.id.tv_more).setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            commentReturnAdapter.getData().clear();
                            commentReturnAdapter.setNewData(replys);
                            holder.getView(R.id.tv_more).setVisibility(GONE);
                        }
                    });
                }

            }
        };
        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.SimpleOnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                dataBean = commonAdapter.getData().get(position);
                new XPopup.Builder(getContext())
                        .hasShadowBg(false) // 去掉半透明背景
                        .asBottomList("", new String[]{"回复", /*"举报",*/ "取消"},
                                null, -1,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        //Toast.makeText(getContext(),text, Toast.LENGTH_SHORT).show();
                                        switch (position) {
                                            case 0:
                                                TAG = 1;
                                                etComment.setFocusable(true);
                                                etComment.setFocusableInTouchMode(true);
                                                etComment.requestFocus();

                                                break;
                                            case 1:
                                                break;
                                            case 2:
                                                break;
                                        }
                                    }
                                })
                        .show();
            }
        });
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(commonAdapter);
    }

    /**
     * 评论回复
     */
    private void replyStore() {
        String inform = etComment.getText().toString().trim();
        if(TextUtils.isEmpty(inform)) {
            ToastUtil.showToast(mContext,"回复不能为空");
            return;
        }
        int id = 0;
        if(dataBean!=null){
            id = dataBean.getId();
        }
        KeyboardUtils.hideSoftInput(etComment);
        HttpData.getInstance().replyStore(id, inform, new AbsCallback<BaseData<ReplyStoreBean>>() {

            @Override
            public void onRealSuccess(BaseData<ReplyStoreBean> data) {
                if(data.isStatus()) {
                    TAG =0;
                    etComment.getText().clear();
                    getComment();
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                   ToastUtil.showToast(mContext,errMsg);
            }
        });
    }

    /**
     * 评论视频
     */
    private void toStore() {
        String inform = etComment.getText().toString().trim();
        if(TextUtils.isEmpty(inform)) {
            ToastUtil.showToast(mContext,"评论不能为空");
            return;
        }
        KeyboardUtils.hideSoftInput(etComment);
        HttpData.getInstance().totore(mVideoId, inform, new AbsCallback<BaseData<StoreBean>>() {

            @Override
            public void onRealSuccess(BaseData<StoreBean> data) {
                if(data.isStatus()) {
                    TAG =0;
                    etComment.getText().clear();
                    getComment();
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {

            }
        });
    }

    /**
     * 获取评论
     */
    private void getComment() {
        HttpData.getInstance().getComment( mVideoId, new ACallback<CommentBean>() {
            @Override
            public void onSuccess(CommentBean data) {
                list.clear();
                if(data.getData()!=null) {
                    list = data.getData();
                }
                if(list.size()>0) {
                    tvNumber.setText(list.size()+"条评论");
                    commonAdapter.setData(list);
                    commonAdapter.notifyDataSetChanged();
                }else {
                    tvNumber.setText("0条评论");
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {

            }
        });
    }

    //完全可见执行
    @Override
    protected void onShow() {
        super.onShow();
    }

    //完全消失执行
    @Override
    protected void onDismiss() {

    }
    @Override
    protected int getMaxHeight() {
        return (int) (XPopupUtils.getWindowHeight(getContext()) * .85f);
    }
}

